package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.ApplicationContextHelper;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.DictQueryVO;
import com.bifang.module.base.common.vo.dict.DictVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.core.helper.ApiModel;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.system.core.dao.model.PersonInfo;
import com.bifang.module.system.core.dao.service.PersonInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.*;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.common.AreaControlVO;
import com.jwsoft.manager.common.vo.eduHouse.*;
import com.jwsoft.manager.common.vo.eduHouseDetail.EduHouseDetailVO;
import com.jwsoft.manager.common.vo.eduSchool.SchoolDistrictQueryVO;
import com.jwsoft.manager.common.vo.eduSchool.SchoolDistrictVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollPre.EduStudentEnrollPreVO;
import com.jwsoft.manager.common.vo.individuation.HouseInterfaceSaveVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduHouseIntegration;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import com.jwsoft.manager.core.integration.common.DygxIntegration;
import com.jwsoft.manager.core.util.EduDesensitizeUtil;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * 房产信息管理业务实现类
 *
 * @author wangtao
 * @since 2022-11-30
 */
@ApiService(funcCode = "eduHouse", title = "房产信息管理")
@Slf4j
public class EduHouseIntegrationImpl implements EduHouseIntegration {

    @Autowired
    public EduHouseService eduHouseService;

    @Autowired
    public DictHelper dictHelper;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    RedisHelper redisHelper;
    @Autowired
    CommonIntegration commonIntegration;

    @Autowired
    EduSystemConfigIntegration eduSystemConfigIntegration;
    @Autowired
    EduHouseDetailService eduHouseDetailService;
    @Autowired
    EduComplaintService eduComplaintService;
    @Autowired
    EduHouseholdService eduHouseholdService;
    @Autowired
    EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    EduAddressService   eduAddressService;

    @Autowired
    EduAddressSchoolService eduAddressSchoolService;

    @Autowired
    EduStudentHouseService eduStudentHouseService;

    @Autowired
    PersonInfoService personInfoService;

    @Autowired
    EduStudentEnrollPreService eduStudentEnrollPreService;

    @Autowired
    OperationCacheIntegration operationCacheIntegration;
    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;
    @Autowired
    DygxIntegration dygxIntegration;

    @Resource
    DictIntegration dictIntegration;

    @Autowired
    EduStudentEnrollFamilyService eduStudentEnrollFamilyService;

    @Autowired
    private EduhHouseService hHouseService;

    @Autowired
    private  EduDataTaskDetailService eduDataTaskDetailService;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());


    public static final String opType = "HOUSE";
    public static final String AUTH_REDIS = "AUTH_HOUSE_REDIS";
    public static final String STATUS_REDIS = "STATUS_HOUSE_REDIS";
    public static final String HOUSE_USE_REDIS = "HOUSE_USE_REDIS";

    public static final String HOUSE_TABLE = "edu_house";


    @Override
    @OpApi(funcCode = "eduHouse0001", title = "房产信息管理分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduHouseVO> getList(EduHouseQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        Integer year = eduHelper.thisYear();
        if (ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(year);
        }

        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        }else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (CollectionUtils.isEmpty(areaCodeList)){
            throw new AppException("必须传入行政区划");
        }
        //取出脱敏字段，判断是否为空
        Boolean desensitizeFlag = vo.getDesensitizeFlag();
        if (desensitizeFlag == null){
            desensitizeFlag = true;
        }
        String orgId = SessionUtil.getSessionInfo().getOrgId();
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),HOUSE_TABLE);
        if (queryHistoryFlag){
            QueryWrapper<EduhHouse> houseQueryWrapper = new QueryWrapper<>();
            Boolean encryptFlag = eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), HOUSE_TABLE);
            if (encryptFlag){
                eduHouseService.queryEncrypt(vo);
            }
            houseQueryWrapper.lambda()
                    .eq(!ObjectUtils.isEmpty(vo.getUseFlag()), EduhHouse::getUseFlag, vo.getUseFlag())
                    .eq(!ObjectUtils.isEmpty(vo.getHouseId()), EduhHouse::getHouseId, vo.getHouseId())
                    .like(!ObjectUtils.isEmpty(vo.getAddress()), EduhHouse::getAddress, Convert.toDBC(vo.getAddress()))
                    //.in(EduhHouse::getAreaCode,areaCodeList)//因市区获取到的房产没有行政区划，所以当前不按行政区划查询
                    .eq(
                            !ObjectUtils.isEmpty(vo.getLandCategories()),
                            EduhHouse::getLandCategories,
                            vo.getLandCategories())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getHouseNature()),
                            EduhHouse::getHouseNature,
                            vo.getHouseNature())
                    .eq(!ObjectUtils.isEmpty(vo.getStreet()), EduhHouse::getStreet, vo.getStreet())
                    .eq(!ObjectUtils.isEmpty(vo.getYear()), EduhHouse::getYear, vo.getYear())
                    .like(
                            !ObjectUtils.isEmpty(vo.getRealProperty()),
                            EduhHouse::getRealProperty,
                            !ObjectUtils.isEmpty(vo.getRealProperty())
                                    ? vo.getRealProperty().replace("（", "(").replace("）", ")")
                                    : "")
                    .eq(
                            !ObjectUtils.isEmpty(vo.getYearLimit()),
                            EduhHouse::getYearLimit,
                            vo.getYearLimit())
                    .eq(!ObjectUtils.isEmpty(vo.getStatus()), EduhHouse::getStatus, vo.getStatus())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getAuthStatus()),
                            EduhHouse::getAuthStatus,
                            vo.getAuthStatus());
            if (!ObjectUtils.isEmpty(vo.getSchoolCategory())) {
                if (vo.getSchoolCategory().equals("2")) {
                    if (vo.getSchoolOrder().equals("1")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduhHouse::getPrimarySchoolOne, orgId)
                                                    .or()
                                                    .isNull(EduhHouse::getPrimarySchoolOne);
                                        });
                    } else if (vo.getSchoolOrder().equals("2")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduhHouse::getPrimarySchoolTwo, orgId)
                                                    .or()
                                                    .isNull(EduhHouse::getPrimarySchoolTwo);
                                        });
                    } else if (vo.getSchoolOrder().equals("3")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduhHouse::getPrimarySchoolThree, orgId)
                                                    .or()
                                                    .isNull(EduhHouse::getPrimarySchoolThree);
                                        });
                    } else if (vo.getSchoolOrder().equals("4")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduhHouse::getPrimarySchoolFour, orgId)
                                                    .or()
                                                    .isNull(EduhHouse::getPrimarySchoolFour);
                                        });
                    }
                } else if (vo.getSchoolCategory().equals("3")) {
                    if (vo.getSchoolOrder().equals("1")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduhHouse::getJuniorSchoolOne, orgId)
                                                    .or()
                                                    .isNull(EduhHouse::getJuniorSchoolOne);
                                        });
                    } else if (vo.getSchoolOrder().equals("2")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduhHouse::getJuniorSchoolTwo, orgId)
                                                    .or()
                                                    .isNull(EduhHouse::getJuniorSchoolTwo);
                                        });
                    } else if (vo.getSchoolOrder().equals("3")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduhHouse::getJuniorSchoolThree, orgId)
                                                    .or()
                                                    .isNull(EduhHouse::getJuniorSchoolThree);
                                        });
                    } else if (vo.getSchoolOrder().equals("4")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduhHouse::getJuniorSchoolFour, orgId)
                                                    .or()
                                                    .isNull(EduhHouse::getJuniorSchoolFour);
                                        });
                    }
                }
            }
            PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
            List<EduhHouse> list = hHouseService.list(houseQueryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            List<EduHouseVO> resultList = new ArrayList<>();
            for (EduhHouse eduhHouse : list) {
                //对字段进行解密
                if(BoolEnum.TRUE.getType().equalsIgnoreCase(eduhHouse.getEncryptFlag())){
                    hHouseService.decrypt(eduhHouse);
                }
                //脱敏
                eduhHouse.setRealProperty(EduDesensitizeUtil.desensitizeOther(eduhHouse.getRealProperty()));
                eduhHouse.setAddress(EduDesensitizeUtil.desensitizeAddress(eduhHouse.getAddress()));
                eduhHouse.setQlrName(EduDesensitizeUtil.desensitizeOther(eduhHouse.getQlrName()));

                //转换返回结果
                EduHouseVO houseVO = Convert.convert(EduHouseVO.class, eduhHouse);
                resultList.add(houseVO);
            }
            resultList.forEach(
                    item -> {
                        if (!ObjectUtils.isEmpty(vo.getSchoolCategory())) {
                            if (vo.getSchoolCategory().equals("2")) {
                                if (vo.getSchoolOrder().equals("1")) {
                                    item.setCheckFlag(orgId.equals(item.getPrimarySchoolOne()));
                                } else if (vo.getSchoolOrder().equals("2")) {
                                    item.setCheckFlag(orgId.equals(item.getPrimarySchoolTwo()));
                                } else if (vo.getSchoolOrder().equals("3")) {
                                    item.setCheckFlag(orgId.equals(item.getPrimarySchoolThree()));
                                } else if (vo.getSchoolOrder().equals("4")) {
                                    item.setCheckFlag(orgId.equals(item.getPrimarySchoolFour()));
                                }
                            } else if (vo.getSchoolCategory().equals("3")) {
                                if (vo.getSchoolOrder().equals("1")) {
                                    item.setCheckFlag(orgId.equals(item.getJuniorSchoolOne()));
                                } else if (vo.getSchoolOrder().equals("2")) {
                                    item.setCheckFlag(orgId.equals(item.getJuniorSchoolTwo()));
                                } else if (vo.getSchoolOrder().equals("3")) {
                                    item.setCheckFlag(orgId.equals(item.getJuniorSchoolThree()));
                                } else if (vo.getSchoolOrder().equals("4")) {
                                    item.setCheckFlag(orgId.equals(item.getJuniorSchoolFour()));
                                }
                            }
                        }
                    });
            // 转义数据字典值
            dictHelper.valueToName(resultList, Arrays.asList(EduHouseEnum.values()));
            PageInfo<EduhHouse> pageInfo = new PageInfo<>(list);
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }else{
            PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
            QueryWrapper<EduHouse> houseQueryWrapper = new QueryWrapper<>();
            houseQueryWrapper
                    .lambda()
                    .eq(!ObjectUtils.isEmpty(vo.getUseFlag()), EduHouse::getUseFlag, vo.getUseFlag())
                    .eq(!ObjectUtils.isEmpty(vo.getHouseId()), EduHouse::getHouseId, vo.getHouseId())
                    .like(!ObjectUtils.isEmpty(vo.getAddress()), EduHouse::getAddress, Convert.toDBC(vo.getAddress()))
                    .in(EduHouse::getAreaCode,areaCodeList)
                    .eq(
                            !ObjectUtils.isEmpty(vo.getLandCategories()),
                            EduHouse::getLandCategories,
                            vo.getLandCategories())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getHouseNature()),
                            EduHouse::getHouseNature,
                            vo.getHouseNature())
                    .eq(!ObjectUtils.isEmpty(vo.getStreet()), EduHouse::getStreet, vo.getStreet())
                    .eq(!ObjectUtils.isEmpty(vo.getYear()), EduHouse::getYear, vo.getYear())
                    .like(
                            !ObjectUtils.isEmpty(vo.getRealProperty()),
                            EduHouse::getRealProperty,
                            !ObjectUtils.isEmpty(vo.getRealProperty())
                                    ? vo.getRealProperty().replace("（", "(").replace("）", ")")
                                    : "")
                    .eq(
                            !ObjectUtils.isEmpty(vo.getYearLimit()),
                            EduHouse::getYearLimit,
                            vo.getYearLimit())
                    .eq(!ObjectUtils.isEmpty(vo.getStatus()), EduHouse::getStatus, vo.getStatus())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getAuthStatus()),
                            EduHouse::getAuthStatus,
                            vo.getAuthStatus());
            if (!ObjectUtils.isEmpty(vo.getSchoolCategory())) {
                if (vo.getSchoolCategory().equals("2")) {
                    if (vo.getSchoolOrder().equals("1")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduHouse::getPrimarySchoolOne, orgId)
                                                    .or()
                                                    .isNull(EduHouse::getPrimarySchoolOne);
                                        });
                    } else if (vo.getSchoolOrder().equals("2")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduHouse::getPrimarySchoolTwo, orgId)
                                                    .or()
                                                    .isNull(EduHouse::getPrimarySchoolTwo);
                                        });
                    } else if (vo.getSchoolOrder().equals("3")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduHouse::getPrimarySchoolThree, orgId)
                                                    .or()
                                                    .isNull(EduHouse::getPrimarySchoolThree);
                                        });
                    } else if (vo.getSchoolOrder().equals("4")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduHouse::getPrimarySchoolFour, orgId)
                                                    .or()
                                                    .isNull(EduHouse::getPrimarySchoolFour);
                                        });
                    }
                } else if (vo.getSchoolCategory().equals("3")) {
                    if (vo.getSchoolOrder().equals("1")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduHouse::getJuniorSchoolOne, orgId)
                                                    .or()
                                                    .isNull(EduHouse::getJuniorSchoolOne);
                                        });
                    } else if (vo.getSchoolOrder().equals("2")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduHouse::getJuniorSchoolTwo, orgId)
                                                    .or()
                                                    .isNull(EduHouse::getJuniorSchoolTwo);
                                        });
                    } else if (vo.getSchoolOrder().equals("3")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduHouse::getJuniorSchoolThree, orgId)
                                                    .or()
                                                    .isNull(EduHouse::getJuniorSchoolThree);
                                        });
                    } else if (vo.getSchoolOrder().equals("4")) {
                        houseQueryWrapper
                                .lambda()
                                .and(
                                        wrapper -> {
                                            wrapper.eq(EduHouse::getJuniorSchoolFour, orgId)
                                                    .or()
                                                    .isNull(EduHouse::getJuniorSchoolFour);
                                        });
                    }
                }
            }


            List<EduHouse> list = eduHouseService.list(houseQueryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduHouse> pageInfo = new PageInfo<>(list);
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduHouseVO> resultList = Convert.toList(EduHouseVO.class, pageInfo.getList());
            resultList.forEach(
                    item -> {
                        if (!ObjectUtils.isEmpty(vo.getSchoolCategory())) {
                            if (vo.getSchoolCategory().equals("2")) {
                                if (vo.getSchoolOrder().equals("1")) {
                                    item.setCheckFlag(orgId.equals(item.getPrimarySchoolOne()));
                                } else if (vo.getSchoolOrder().equals("2")) {
                                    item.setCheckFlag(orgId.equals(item.getPrimarySchoolTwo()));
                                } else if (vo.getSchoolOrder().equals("3")) {
                                    item.setCheckFlag(orgId.equals(item.getPrimarySchoolThree()));
                                } else if (vo.getSchoolOrder().equals("4")) {
                                    item.setCheckFlag(orgId.equals(item.getPrimarySchoolFour()));
                                }
                            } else if (vo.getSchoolCategory().equals("3")) {
                                if (vo.getSchoolOrder().equals("1")) {
                                    item.setCheckFlag(orgId.equals(item.getJuniorSchoolOne()));
                                } else if (vo.getSchoolOrder().equals("2")) {
                                    item.setCheckFlag(orgId.equals(item.getJuniorSchoolTwo()));
                                } else if (vo.getSchoolOrder().equals("3")) {
                                    item.setCheckFlag(orgId.equals(item.getJuniorSchoolThree()));
                                } else if (vo.getSchoolOrder().equals("4")) {
                                    item.setCheckFlag(orgId.equals(item.getJuniorSchoolFour()));
                                }
                            }
                        }
                    });
            // 转义数据字典值
            dictHelper.valueToName(resultList, Arrays.asList(EduHouseEnum.values()));
            //脱敏
            if (desensitizeFlag){
                for (EduHouseVO eduHouseVO : resultList) {
                    eduHouseVO.setRealProperty(EduDesensitizeUtil.desensitizeOther(eduHouseVO.getRealProperty()));
                    eduHouseVO.setAddress(EduDesensitizeUtil.desensitizeAddress(eduHouseVO.getAddress()));
                    eduHouseVO.setQlrName(EduDesensitizeUtil.desensitizeOther(eduHouseVO.getQlrName()));
                }
            }
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }
    }

    @Override
    @OpApi(funcCode = "eduHouse0002", title = "房产信息管理根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduHouseVO getById(EduHouseKeyVO vo) {
        EduHouse entity = eduHouseService.getById(vo.getHouseId());
        if (ObjectUtils.isEmpty(entity)) {
            //在线表查不到，去查一遍历史表
            EduhHouse eduhHouse = hHouseService.getById(vo.getHouseId());
            if (ObjectUtils.isEmpty(eduhHouse)){
                throw new AppException("查询不到详细信息!");
            }
            if (BoolEnum.TRUE.getType().equalsIgnoreCase(eduhHouse.getEncryptFlag())){
                hHouseService.decrypt(eduhHouse);
            }
            return  Convert.convert(EduHouseVO.class, eduhHouse);
        }
        EduHouseVO result = Convert.convert(EduHouseVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduHouse0003", title = "房产信息管理保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduHouseVO vo) {
        if (vo.getYear()==null){
            throw new AppException("所属招生年度不能为空");
        }
        Integer year=eduHelper.thisYear();
        if (year-vo.getYear()!=0) {
            throw new AppException("只能维护招生当前年度的数据!");
        }
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduHouse0004", title = "房产信息管理新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduHouse0004",
            operationName = "房产信息管理新增",
            dataType = "houseId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduHouseVO add(EduHouseVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        EduHouse entity = Convert.convert(EduHouse.class, vo);
        String addressId =
                eduAddressService.saveByAddress(vo.getAddress(),vo.getYear(),"1","1");
        entity.setAddressId(addressId);
        eduHouseService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setHouseId(entity.getHouseId());
        clearCache(entity.getHouseId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduHouse0005", title = "房产信息管理修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduHouse0005",
            operationName = "房产信息管理修改",
            dataType = "houseId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduHouseVO edit(EduHouseVO vo) {
        if (ObjectUtils.isEmpty(vo.getHouseId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduHouse oldEntity = eduHouseService.getById(vo.getHouseId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduHouse entity = Convert.convert(EduHouse.class, vo);
        String addressId =
                eduAddressService.saveByAddress(vo.getAddress(),vo.getYear(),"1","1");
        entity.setAddressId(addressId);
        eduHouseService.updateById(entity);
        UpdateWrapper<EduHouseDetail> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().eq(EduHouseDetail::getHouseId,entity.getHouseId())
                .set(EduHouseDetail::getStatus,entity.getStatus());
        eduHouseDetailService.update(updateWrapper);
        clearCache(entity.getHouseId());
        return vo;
    }

    //清除缓存
    private void clearCache(String houseId){
        //查询人员
        if(StringUtils.isBlank(houseId)){
            return;
        }
        QueryWrapper<EduHouseDetail> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().select(EduHouseDetail::getIdcard).eq(EduHouseDetail::getHouseId,houseId);
        List<EduHouseDetail> details=eduHouseDetailService.list(queryWrapper);
        if(CollectionUtils.isEmpty(details)){
            return;
        }
        List<String> idcardList=details.stream().map(EduHouseDetail::getIdcard).distinct().collect(Collectors.toList());
        QueryWrapper<EduStudentEnrollPre> queryPreWrapper=new QueryWrapper<>();
        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId,EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear,eduHelper.thisYear())
                .and( wrapper -> {
                    wrapper.in(EduStudentEnrollPre::getIdcard, idcardList)
                            .or()
                            .in(EduStudentEnrollPre::getFatherIdcard, idcardList)
                            .or()
                            .in(EduStudentEnrollPre::getMotherIdcard, idcardList);
                });
        List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryPreWrapper);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        for (EduStudentEnrollPre pre:list) {
            //房产
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }
    }
    @Override
    @OpApi(funcCode = "eduHouse0006", title = "房产信息管理根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduHouse0006",
            operationName = "房产信息管理删除",
            dataType = "houseId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduHouseKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getHouseId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduHouse entity = eduHouseService.getById(vo.getHouseId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduHouseService.removeById(vo.getHouseId());
        clearCache(entity.getHouseId());
    }

    @Override
    @OpApi(funcCode = "eduHouse0007", title = "批量查询并保存三年内是否使用房产", funcType = FuncTypeEnum.edit)
    public void getAndSaveBatchHouseUse(EduHouseQueryVO vo) {
        List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
        List<String> areaCodeList = selectVOList.stream()
                .map(SelectVO::getDictKey)
                .collect(Collectors.toList());
        String sessionAreaCode = SessionUtil.getAreaCode();
        if (!areaCodeList.contains(sessionAreaCode)) {
            areaCodeList.add(sessionAreaCode);
        }
        vo.setAreaCodeList(areaCodeList);
        this.saveAndSaveBatchHouseUse(vo);
    }

    @Override
    public void saveAndSaveBatchHouseUse(EduHouseQueryVO vo) {
        if (redisHelper.hasKey(HOUSE_USE_REDIS)) {
            throw new AppException("上一笔业务未执行完成，请稍后再试");
        }
        redisHelper.set(HOUSE_USE_REDIS, "1", 600);
        try {
            Integer year = eduHelper.thisYear();

            QueryWrapper<EduHouse> houseQueryWrapper = new QueryWrapper<>();
            houseQueryWrapper
                    .lambda().select(EduHouse::getHouseId,EduHouse::getRealPropertyNum,EduHouse::getRegisterDate,EduHouse::getAddress,EduHouse::getRealProperty)
                    .eq(EduHouse::getUseQueryFlag, BoolEnum.FALSE.getType())
                    .eq(EduHouse::getStatus, BoolEnum.TRUE.getType())
                    .eq(EduHouse::getYear, year)
                    .in(!CollectionUtils.isEmpty( vo.getAreaCodeList()),EduHouse::getAreaCode, vo.getAreaCodeList())
                    .eq(StringUtils.isNotBlank(vo.getAreaCode()),EduHouse::getAreaCode,vo.getAreaCode());
            List<EduHouse> houseList = eduHouseService.list(houseQueryWrapper);
            log.warn("房产锁定执行中......");
            for (EduHouse house : houseList) {
                if (!ObjectUtils.isEmpty(house.getRegisterDate())
                        && DateUtil.year(house.getRegisterDate()) < year - 3) {
                    //登记时间是3年前的数据不比对
                    house.setUseFlag(BoolEnum.FALSE.getType());
                    house.setUseQueryFlag(BoolEnum.TRUE.getType());
                    house.setUseQueryRemark("登记时间超过三年直接认为是未使用");
                } else {
                    List<EduHouse> studentHouseList = eduHouseService.getUseList(year,year-2,vo.getAreaCode(),house.getAddress(),house.getRealPropertyNum());

                    QueryWrapper<EduHouseDetail> detailQueryWrapper = new QueryWrapper<>();
                        detailQueryWrapper
                                .lambda()
                                .eq(EduHouseDetail::getHouseId, house.getHouseId());
                        List<EduHouseDetail> detailList=eduHouseDetailService.list(detailQueryWrapper);
                        List<String> studentHouseIdList=new ArrayList<>();
                        if(StringUtils.isNotBlank(house.getRealPropertyNum())){
                            for(EduHouse studentHouse:studentHouseList){
                                if(StringUtils.isNotBlank(studentHouse.getRealPropertyNum())&&studentHouse.getRealPropertyNum().equals(house.getRealPropertyNum())){
                                    studentHouseIdList.add(studentHouse.getHouseId());
                                    break;
                                }
                            }
                        }else{
                            for(EduHouse studentHouse:studentHouseList){
                                if(StringUtils.isNotBlank(studentHouse.getAddress())&&studentHouse.getAddress().equals(house.getAddress())){
                                    studentHouseIdList.add(studentHouse.getHouseId());
                                }
                            }
                        }

                        if(!CollectionUtils.isEmpty(studentHouseIdList)&&!CollectionUtils.isEmpty(detailList)){
                            List<String> idcardList=new ArrayList<>();
                            List<String> nameList=new ArrayList<>();
                            for(EduHouseDetail eduHouseDetail:detailList){
                                if(StringUtils.isNotBlank(eduHouseDetail.getIdcard())){
                                    idcardList.add(eduHouseDetail.getIdcard());
                                }
                                if(StringUtils.isNotBlank(eduHouseDetail.getFullName())){
                                    nameList.add(eduHouseDetail.getFullName());
                                }
                            }
                            QueryWrapper<EduHouseDetail> studentDetailQuery=new QueryWrapper<>();
                            if(!CollectionUtils.isEmpty(idcardList)){
                                studentDetailQuery.lambda().in(EduHouseDetail::getHouseId,studentHouseIdList)
                                        .in(EduHouseDetail::getIdcard,idcardList);
                                if(eduHouseDetailService.count(studentDetailQuery)>0){
                                    house.setUseFlag(BoolEnum.FALSE.getType());
                                    house.setUseQueryFlag(BoolEnum.TRUE.getType());
                                    house.setUseQueryRemark("比对成功，至少有一个身份证一致设置为未使用");
                                }else{
                                    house.setUseFlag(BoolEnum.TRUE.getType());
                                    house.setUseQueryFlag(BoolEnum.TRUE.getType());
                                    house.setUseQueryRemark("比对成功，身份证都不一致，设置为已使用");
                                }
                            }else {
                                studentDetailQuery.lambda().in(EduHouseDetail::getHouseId,studentHouseIdList)
                                        .in(EduHouseDetail::getFullName,nameList);
                                if(eduHouseDetailService.count(studentDetailQuery)>0){
                                    house.setUseFlag(BoolEnum.FALSE.getType());
                                    house.setUseQueryFlag(BoolEnum.TRUE.getType());
                                    house.setUseQueryRemark("比对成功，因身份证为空，使用姓名比对，至少有一个姓名一致设置为未使用");
                                }else{
                                    house.setUseFlag(BoolEnum.TRUE.getType());
                                    house.setUseQueryFlag(BoolEnum.TRUE.getType());
                                    house.setUseQueryRemark("比对成功，，因身份证为空，使用姓名比对，姓名都不一致，设置为已使用");
                                }
                            }


                        }else{
                            house.setUseFlag(BoolEnum.FALSE.getType());
                            house.setUseQueryFlag(BoolEnum.TRUE.getType());
                            house.setUseQueryRemark("比对成功，未使用");
                        }



                    }

                UpdateWrapper<EduHouse> updateWrapper=new UpdateWrapper<>();
                updateWrapper.lambda().eq(EduHouse::getHouseId,house.getHouseId())
                        .set(EduHouse::getUseFlag,house.getUseFlag())
                        .set(EduHouse::getUseQueryRemark,house.getUseQueryRemark())
                        .set(EduHouse::getUseQueryFlag,house.getUseQueryFlag());
                eduHouseService.update(updateWrapper);
            }

        }catch (Exception e) {
            log.warn("房产锁定异常",e);
            throw e;
        } finally {
            redisHelper.del(HOUSE_USE_REDIS);
        }
    }

    @Override
    @OpApi(funcCode = "eduHouse0017", title = "清除房产锁定过程缓存", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public void clearUse(EduHouseQueryVO vo) {
        redisHelper.del(HOUSE_USE_REDIS);
    }


    @Override
    @OpApi(funcCode = "eduHouse0008", title = "批量审核房产", funcType = FuncTypeEnum.edit)
    @SaveOplog(
            operationType = "eduHouse0008",
            operationName = "批量审核房产",
            dataType = "houseId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void auditBatchHouse(HouseAuditVO vo){
        if (redisHelper.hasKey(AUTH_REDIS)) {
            throw new AppException("上一笔业务未执行完成，请稍后再试");
        }
        redisHelper.set(AUTH_REDIS, "1", 300);
        try {
            List<String> houseIdList = vo.getHouseIdList();
            List<EduHouse> houseList = eduHouseService.listByIds(houseIdList);
            houseList.forEach(
                    item -> {
                        item.setRemark("人工核验："+vo.getAuthRemarks());
                        item.setAuthStatus(vo.getAuthStatus());
                        clearCache(item.getHouseId());
                    });
            eduHouseService.updateBatchById(houseList);
        } catch (Exception e) {
            throw e;
        } finally {
            redisHelper.del(AUTH_REDIS);
        }
    }

    @Override
    @OpApi(funcCode = "eduHouse0009", title = "批量改房产有效无效", funcType = FuncTypeEnum.edit)
    @SaveOplog(
            operationType = "eduHouse0009",
            operationName = "批量改房产有效无效",
            dataType = "houseId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void updateStatusBatchHouse(HouseUpdateStatusVO vo){
        if (redisHelper.hasKey(STATUS_REDIS)) {
            throw new AppException("上一笔业务未执行完成，请稍后再试");
        }
        redisHelper.set(STATUS_REDIS, "1", 300);
        try {
            List<String> houseIdList = vo.getHouseIdList();
            List<EduHouse> houseList = eduHouseService.listByIds(houseIdList);
            List<String> addressList = new ArrayList<>();
            QueryWrapper<EduHouseDetail> houseDetailQueryWrapper = new QueryWrapper<>();
            houseDetailQueryWrapper
                    .lambda()
                    .in(EduHouseDetail::getHouseId, houseIdList)
                    .eq(EduHouseDetail::getStatus, BoolEnum.TRUE.getType());
            List<EduHouseDetail> detailList = eduHouseDetailService.list(houseDetailQueryWrapper);

            for (EduHouse eduHouse : houseList) {
                eduHouse.setStatus(vo.getStatus());
                eduHouse.setRemark("人工核验");
                String address = eduHouse.getAddress();
                if (BoolEnum.FALSE.getType().equals(vo.getStatus())) {
                    QueryWrapper<EduHousehold> householdQueryWrapper = new QueryWrapper<>();
                    householdQueryWrapper
                            .lambda()
                            .eq(EduHousehold::getAddress, address)
                            .eq(EduHousehold::getYear, eduHouse.getYear());
                    long count = eduHouseholdService.count(householdQueryWrapper);
                    QueryWrapper<EduHouse> eduHouseQueryWrapper = new QueryWrapper<>();
                    eduHouseQueryWrapper
                            .lambda()
                            .eq(EduHouse::getAddress, address)
                            .ne(EduHouse::getHouseId,eduHouse.getHouseId())
                            .eq(EduHouse::getYear, eduHouse.getYear())
                            .eq(EduHouse::getStatus, BoolEnum.TRUE.getType());
                    long countHouse = eduHouseService.count(eduHouseQueryWrapper);
                    if (count <= 0&&countHouse<=0) {
                        //                        QueryWrapper<EduHousehold>
                        // householdQueryWrapper
                        QueryWrapper<EduAddress> addressQueryWrapper = new QueryWrapper<>();
                        addressQueryWrapper
                                .lambda()
                                .eq(EduAddress::getAddressName, address);
                        EduAddress eduAddress =
                                eduAddressService.getOne(addressQueryWrapper, false);
                        if (!ObjectUtils.isEmpty(eduAddress)) {
                            addressList.add(eduAddress.getAddressId());
                        }

                        QueryWrapper<EduAddressSchool> addressSchoolQueryWrapper =
                                new QueryWrapper<>();
                        addressSchoolQueryWrapper
                                .lambda()
                                .eq(EduAddressSchool::getAddressName, address)
                                .select(EduAddressSchool::getAddressSchoolId);
                        List<String> addressSchoolIdList =
                                eduAddressSchoolService
                                        .list(addressSchoolQueryWrapper)
                                        .stream()
                                        .map(EduAddressSchool::getAddressSchoolId)
                                        .collect(Collectors.toList());
                        eduAddressSchoolService.removeByIds(addressSchoolIdList);
                    }
                }
                if (BoolEnum.TRUE.getType().equals(vo.getStatus())) {
                    List<String> idcardList=new ArrayList<>();
                    for(EduHouseDetail detail:detailList){
                        if(detail.getHouseId().equals(eduHouse.getHouseId())){
                            if(StringUtils.isNotBlank(detail.getIdcard())){
                                idcardList.add(detail.getIdcard());
                            }
                        }
                    }
                    String bnxxFlag="0";
                    String bnczFlag="0";
                    if (!CollectionUtils.isEmpty(idcardList)){
                        QueryWrapper<EduStudentEnrollPre> queryPreWrapper=new QueryWrapper<>();
                        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId,EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getMotherIdcard)
                                .eq(EduStudentEnrollPre::getYear,eduHelper.thisYear())
                                .and( wrapper -> {
                                    wrapper.in(EduStudentEnrollPre::getIdcard, idcardList)
                                            .or()
                                            .in(EduStudentEnrollPre::getFatherIdcard, idcardList)
                                            .or()
                                            .in(EduStudentEnrollPre::getMotherIdcard, idcardList);
                                });
                        List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryPreWrapper);
                        if (!CollectionUtils.isEmpty(list)){
                            for(EduStudentEnrollPre pre:list){
                                if(SchoolCategoryEnum.PRIMARY.getType().equals(pre.getSchoolCategory())){
                                    bnxxFlag="1";
                                }
                                if(SchoolCategoryEnum.JUNIOR.getType().equals(pre.getSchoolCategory())){
                                    bnczFlag="1";
                                }
                            }
                        }
                    }
                    String adressId = eduAddressService.saveByAddress(address,eduHouse.getYear(),bnxxFlag,bnczFlag);
                    eduHouse.setAddressId(adressId);
                    eduHouse.setUseQueryFlag(BoolEnum.FALSE.getType());
                    eduHouse.setUseFlag(BoolEnum.FALSE.getType());
                }
                clearCache(eduHouse.getHouseId());
            }
            if (detailList.size() > 0) {
                detailList.forEach(
                        item -> {
                            item.setStatus(vo.getStatus());
                        });
                eduHouseDetailService.updateBatchById(detailList);
            }
            eduHouseService.updateBatchById(houseList);
            if (BoolEnum.FALSE.getType().equals(vo.getStatus())) {
                eduAddressService.removeByIds(addressList);
            }



        } catch (Exception e) {
            throw e;
        } finally {
            redisHelper.del(STATUS_REDIS);
        }
    }

    @Override
    @OpApi(funcCode = "eduHouse0010", title = "学生房产使用生成", funcType = FuncTypeEnum.other)
    public void initUseHouse(StudentHouseQueryVO vo){
        if(vo.getYear()==null){
            throw new AppException("生成年度不能为空");
        }
        if(redisHelper.hasKey("initUserHouse")){
            throw new AppException("学生房产使用正在生成中，请稍后查看");
        }
        redisHelper.set("initUserHouse",vo.getYear(),3600);
        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        logger.info("线程池创建成功");
        try{
            CompletableFuture<Void> initHouseIdUserHouse = CompletableFuture.runAsync(() -> {
                //处理houseId不为空的数据
                this.initUseHouse(Integer.parseInt(vo.getYear()));
                logger.info("initUseHouse处理完成");
            }, executorService);
            CompletableFuture<Void> initNoHouseIdUserHouse = CompletableFuture.runAsync(() -> {
                //处理houseId不为空的数据
                this.initNoUserIdUserHouse(Integer.parseInt(vo.getYear()));
                logger.info("initNoUserIdUserHouse处理完成");
            }, executorService);
            //allOf等待所有数据处理完成
            CompletableFuture<Void> completableFuture = CompletableFuture.allOf(initHouseIdUserHouse, initNoHouseIdUserHouse);
            //get()方法是阻塞的，会等待所有任务完成后才继续执行后续代码。
            completableFuture.get();
        }catch (AppException e){
            throw new AppException(e);
        }catch (Exception e){
          throw new RuntimeException(e);
        } finally {
            //删除锁
            redisHelper.del("initUserHouse");
            // 关闭线程池
            executorService.shutdown();
            try {
                if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                    executorService.shutdownNow();
                    if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                        logger.error("线程池无法正常关闭");
                    }
                }
            } catch (InterruptedException ex) {
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }
            logger.info("线程池正常关闭");
        }
    }

    @Override
    @OpApi(funcCode = "eduHouse0011", title = "根据预采集id获取房产接口信息并保存", funcType = FuncTypeEnum.other)
    @Transactional
    public void saveHouseByPre(EduHousePreVO vo) {
        if (StringUtils.isBlank(vo.getStudentEnrollPreId())) {
            throw new AppException("预采集id不能为空");
        }
        EduStudentEnrollPre eduStudentEnrollPre =
                eduStudentEnrollPreService.getById(vo.getStudentEnrollPreId());
        if (eduStudentEnrollPre == null) {
            throw new AppException("未找到预采集数据");
        }
        if (!AuthStatusEnum.YES.getType().equals(eduStudentEnrollPre.getAuthStatus())) {
            throw new AppException("该预采集未审核或者审核不通过");
        }
        if (vo.getCheckBm()==null){
            vo.setCheckBm(true);
        }
        //判断当前年度是否已报名
        Boolean flag=this.checkEnroll(eduStudentEnrollPre.getIdcard(),eduStudentEnrollPre.getYear());
        if(flag&&vo.getCheckBm()){
            throw new AppException("已报名，不能同步房产信息数据");
        }
        List<String> allIdcardList =new ArrayList<>();

        allIdcardList.add(eduStudentEnrollPre.getIdcard());
        List<String> allNameList = new ArrayList<>();
        allNameList.add(eduStudentEnrollPre.getFullName());
        Boolean oneFlag =false;
        EduStudentEnrollPreVO enrollPreVO = new EduStudentEnrollPreVO();
        BeanUtil.copyProperties(eduStudentEnrollPre,enrollPreVO, CopyOptions.create().ignoreNullValue());
        if (StringUtils.isBlank(enrollPreVO.getFatherIdcard())) {
            oneFlag = true;
        } else {
            allIdcardList.add(enrollPreVO.getFatherIdcard());
            allNameList.add(enrollPreVO.getFatherName());
        }
        if (StringUtils.isBlank(enrollPreVO.getMotherIdcard())) {
            oneFlag = true;
        } else {
            allIdcardList.add(enrollPreVO.getMotherIdcard());
            allNameList.add(enrollPreVO.getMotherName());
        }

        HouseInterfaceSaveVO saveVO = new HouseInterfaceSaveVO();
        saveVO.setIdcard(enrollPreVO.getIdcard());
        saveVO.setName(enrollPreVO.getFullName());
        saveVO.setFatherIdcard(enrollPreVO.getFatherIdcard());
        saveVO.setFatherName(enrollPreVO.getFatherName());
        saveVO.setMotherIdcard(enrollPreVO.getMotherIdcard());
        saveVO.setAreaCode(eduStudentEnrollPre.getAreaCode());
        saveVO.setMotherName(enrollPreVO.getMotherName());
        saveVO.setOneFlag(oneFlag);
        saveVO.setAllIdcardList(allIdcardList);
        saveVO.setAllNameList(allNameList);
        saveVO.setStudentEnrollPreId(vo.getStudentEnrollPreId());
        saveVO.setReqIp(vo.getReqIp());
        if(StringUtils.isBlank(saveVO.getAreaCode())){
            saveVO.setAreaCode(eduHelper.thisAreaCode());
        }
        ApiModel apiModel=eduHelper.getEduFunc("saveHouseInterfaceData",saveVO.getAreaCode());
        try {
            Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
            if (null != bean) {
                apiModel.getMethod().invoke(bean, saveVO);
                if(StringUtils.isNotBlank(vo.getStudentEnrollPreId())){
                    //同步数据后把比对标识改为未比对
                    UpdateWrapper<EduStudentEnrollPre> updateWrapper=new UpdateWrapper<>();
                    updateWrapper.lambda().eq(EduStudentEnrollPre::getStudentEnrollPreId,vo.getStudentEnrollPreId())
                            .set(EduStudentEnrollPre::getHouseSyncFlag,BoolEnum.TRUE.getType())
                            .set(EduStudentEnrollPre::getBeforeFlag,BoolEnum.FALSE.getType());
                    EduStudentEnrollPre pre=eduStudentEnrollPreService.getById(vo.getStudentEnrollPreId());
                    if(pre!=null&&!"2".equalsIgnoreCase(pre.getConsistentType())){
                        //人工处理过的数据，不重新比对
                        updateWrapper.lambda().set(EduStudentEnrollPre::getConsistentFlag,BoolEnum.FALSE.getType())
                                .set(EduStudentEnrollPre::getHouseId,null);
                    }
                    eduStudentEnrollPreService.update(updateWrapper);
                }
            }else {
                throw new AppException("未查询到方法");
            }
        }catch (AppException e ){
            throw e;
        }catch (InvocationTargetException e ){
            try{
                AppException exception= (AppException) e.getTargetException();
                throw new AppException(exception.getMsg(),e.getTargetException());
            }catch (Exception ex){
                throw new AppException(e.getCause().getMessage(),e.getTargetException());
            }

        }catch (Exception e ){
            throw new AppException( e.getMessage(),e);
        }
        if(StringUtils.isNotBlank(saveVO.getIdcard())){
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(saveVO.getIdcard());

        }
        if(StringUtils.isNotBlank(saveVO.getFatherIdcard())){
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(saveVO.getFatherIdcard());

        }
        if(StringUtils.isNotBlank(saveVO.getMotherIdcard())){
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(saveVO.getMotherIdcard());
        }
        eduEnrollClearCacheHelper.clearCachePreBefore(vo.getStudentEnrollPreId());
    }


    @Override
    public String saveDict(String dictField, String dictValue, String accessToken) {
        if (ObjectUtils.isEmpty(dictValue)) {
            return dictValue;
        }
        DictQueryVO dictQueryVO = new DictQueryVO();
        dictQueryVO.setDictField(dictField);
        dictQueryVO.setDictValue(dictValue);
        String key = dictIntegration.getKey(dictQueryVO);
        if (!ObjectUtils.isEmpty(key)) {
            return key;
        } else {
            List<SelectVO> dictList = dictIntegration.getDictByDictField(dictQueryVO);
            int maxKey =
                    dictList.stream()
                            .mapToInt(item -> Integer.parseInt(item.getDictKey()))
                            .max()
                            .getAsInt();
            DictVO dictVO = Convert.convert(DictVO.class, dictList.get(0));
            dictVO.setSysId(null);
            dictVO.setDictKey(maxKey + 1 + "");
            dictVO.setDictValue(dictValue);
            dictVO.setAccessToken(accessToken);
            dictIntegration.add(dictVO);
            return dictVO.getDictKey();
        }
    }

    @Override
    @OpApi(funcCode = "eduHouse0012", title = "当年适龄子女我的房产", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE,savelog = false)
    public List<EduHouseVO> getMyHouseInfo(AreaControlVO baseVO) {
        String idcard = SessionUtil.getSessionInfo().getIdcard();
        if(StringUtils.isBlank(idcard)){
            throw new AppException("用户的证件号码不能为空");
        }
        String key=idcard;
        Cache<String, List<EduHouseVO>> cache = JetCacheUtils.create(EduCache.EDU_MY_ENROLL_PRE_HOUSE, CacheType.BOTH, Duration.ofHours(6), Duration.ofSeconds(20));
        List<EduHouseVO> value=  cache.get(key);
        if(value!=null){
            return value;
        }
        if(StringUtils.isBlank(baseVO.getAreaCode())){
            //获取当前部署行政区划
            baseVO.setAreaCode(eduHelper.thisAreaCode());
        }
        EduOperationCacheQueryVO queryOpVO=new EduOperationCacheQueryVO();
        queryOpVO.setOperating("YW024");
        queryOpVO.setAreaCode(baseVO.getAreaCode());
        queryOpVO.setClassify("2");
        EduOperationCacheDetailVO fcOption=eduSystemConfigIntegration.getEduOperationOne(queryOpVO);
        int year=fcOption.getYear();
        QueryWrapper<EduStudentEnrollPre> studentEnrollPreQueryWrapper = new QueryWrapper<>();
        studentEnrollPreQueryWrapper
                .lambda()
                .eq(EduStudentEnrollPre::getYear, year)
                .and(
                        wrapper -> {
                            wrapper.eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                        });
        List<EduStudentEnrollPre> queryList =
                eduStudentEnrollPreService.list(studentEnrollPreQueryWrapper);

        if (CollectionUtils.isEmpty(queryList)) {
            cache.put(key,new ArrayList<>());
            return new ArrayList<>();
        }
        List<String> idcardList = new ArrayList<>();
        List<String> fmList = new ArrayList<>();
        List<String> xdList = new ArrayList<>();
        List<String> childList=new ArrayList<>();
        for (EduStudentEnrollPre pre : queryList) {
            idcardList.add(pre.getIdcard());
            childList.add(pre.getIdcard());
            if (StringUtils.isNotBlank(pre.getFatherIdcard())) {
                if (!fmList.contains(pre.getFatherIdcard())) {
                    fmList.add(pre.getFatherIdcard());
                }
            }
            if (StringUtils.isNotBlank(pre.getMotherIdcard())) {
                if (!fmList.contains(pre.getMotherIdcard())) {
                    fmList.add(pre.getMotherIdcard());
                }
            }
            if (!xdList.contains(pre.getSchoolCategory())) {
                xdList.add(pre.getSchoolCategory());
            }
        }
        idcardList.addAll(fmList);
        //去系统参数判断是否只能查询自己的房产
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("only_my_house_enroll");
        String onlyflag = commonIntegration.getValueByKey(commonVO);
        QueryWrapper<EduHouseDetail> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper
                .lambda()
                .eq(EduHouseDetail::getYear, year)
                .eq(EduHouseDetail::getStatus, BoolEnum.TRUE.getType());
        if("0".equalsIgnoreCase(onlyflag)||"false".equalsIgnoreCase(onlyflag)){
            detailQueryWrapper
                    .lambda()
                    .in(EduHouseDetail::getIdcard, idcardList);
        }else{
            List<String> cList=new ArrayList<>();
            cList.add(idcard);
            cList.addAll(childList);
            detailQueryWrapper
                    .lambda()
                    .in(EduHouseDetail::getIdcard, cList);
        }
        List<EduHouseDetail> detailList = eduHouseDetailService.list(detailQueryWrapper);
        if (CollectionUtils.isEmpty(detailList)) {
            return new ArrayList<>();
        }
        List<String> authList=new ArrayList<>();
        authList.add(AuthStatusEnum.NODO.getType());
        authList.add(AuthStatusEnum.YES.getType());
        QueryWrapper<EduHouse> houseQueryWrapper=new QueryWrapper<>();
        houseQueryWrapper.lambda().in(EduHouse::getHouseId,detailList.stream().map(EduHouseDetail::getHouseId).distinct().collect(Collectors.toList()))
                .eq(EduHouse::getStatus,BoolEnum.TRUE.getType())
                .in(EduHouse::getAuthStatus,authList)
                .eq(EduHouse::getYear,year);
        List<EduHouse> houseList = eduHouseService.list(houseQueryWrapper);
        if(CollectionUtils.isEmpty(houseList)){
            cache.put(key,new ArrayList<>());
            return new ArrayList<>();
        }
        List<EduHouseVO> houseVOList =
                Convert.toList(
                        EduHouseVO.class,
                        houseList);

        // 获取学区信息
        Map<String, List<SchoolDistrictVO>> groupBy = new HashMap<>();
        if (!CollectionUtils.isEmpty(houseVOList)) {

            // 没有年度参数则不获取房产学区
            Long houseEndTime =null;
            if(fcOption!=null&&fcOption.getEndTime()!=null){
                houseEndTime=fcOption.getEndTime().getTime()/1000;
            }
            if (houseEndTime != null) {
                List<String> addressIdList =
                        houseVOList.stream()
                                .map(EduHouseVO::getAddressId)
                                .distinct()
                                .collect(Collectors.toList());
                SchoolDistrictQueryVO queryVO = new SchoolDistrictQueryVO();
                queryVO.setAddressIdList(addressIdList);
                queryVO.setSchoolCategoryList(xdList);
                List<SchoolDistrictVO> schoolDistrictVOList =
                        eduAddressSchoolService.getSchoolInfo(queryVO);
                if (!CollectionUtils.isEmpty(schoolDistrictVOList)) {
                    dictHelper.valueToName(
                            schoolDistrictVOList, Arrays.asList(SchoolDictEnum.values()));
                    groupBy =
                            schoolDistrictVOList.stream()
                                    .collect(Collectors.groupingBy(SchoolDistrictVO::getAddressId));
                }
            }
            List<String> houseIdList =
                    houseVOList.stream().map(EduHouseVO::getHouseId).collect(Collectors.toList());
            QueryWrapper<EduComplaint> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .lambda().select(EduComplaint::getHandleStatus,EduComplaint::getOtherId)
                    .eq(EduComplaint::getType, '3')
                    .eq(EduComplaint::getHandleStatus, BoolEnum.FALSE.getType())
                    .in(EduComplaint::getOtherId, houseIdList);
            List<EduComplaint> complaints = eduComplaintService.list(queryWrapper);
            Map<String, String> complainMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(complaints)) {
                complainMap =
                        complaints.stream()
                                .collect(
                                        Collectors.toMap(
                                                EduComplaint::getOtherId,
                                                EduComplaint::getHandleStatus,
                                                (k1, k2) -> k1));
            }
            QueryWrapper<EduComplaint> queryInfoWrapper = new QueryWrapper<>();
            queryInfoWrapper
                    .lambda().select(EduComplaint::getHandleStatus,EduComplaint::getOtherId)
                    .eq(EduComplaint::getType, '2')
                    .eq(EduComplaint::getHandleStatus, BoolEnum.FALSE.getType())
                    .in(EduComplaint::getOtherId, houseIdList);
            List<EduComplaint> complaintsInfo = eduComplaintService.list(queryInfoWrapper);
            Map<String, String> complainInfoMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(complaintsInfo)) {
                complainInfoMap =
                        complaintsInfo.stream()
                                .collect(
                                        Collectors.toMap(
                                                EduComplaint::getOtherId,
                                                EduComplaint::getHandleStatus,
                                                (k1, k2) -> k1));
            }
            //获取报名情况
            QueryWrapper<EduStudentEnroll> enrollQueryWrapper=new QueryWrapper<>();
            List<String> enrollStatusList=new ArrayList<>();
            enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
            enrollQueryWrapper.lambda().select(EduStudentEnroll::getHouseId)
                    .in(EduStudentEnroll::getIdcard,childList)
                    .in(EduStudentEnroll::getEnrollStatus,enrollStatusList)
                    .isNotNull(EduStudentEnroll::getHouseId)
                    .eq(EduStudentEnroll::getYear,year);
            List<EduStudentEnroll> eduStudentEnrollList= eduStudentEnrollService.list(enrollQueryWrapper);
            List<String> enrollHouseIds=new ArrayList<>();
            if(!CollectionUtils.isEmpty(eduStudentEnrollList)){
                enrollHouseIds=eduStudentEnrollList.stream().map(EduStudentEnroll::getHouseId).distinct().collect(Collectors.toList());
            }
            for (EduHouseVO houseVO : houseVOList) {
                if(enrollHouseIds.contains(houseVO.getHouseId())){
                    houseVO.setEnrollFlag(true);
                }else{
                    houseVO.setEnrollFlag(false);
                }
                houseVO.setHouseHandleStatus(complainMap.get(houseVO.getHouseId()));
                houseVO.setHouseInfoHandleStatus(complainInfoMap.get(houseVO.getHouseId()));
                Boolean attendFlag = true;
                if (houseEndTime != null && houseVO.getRegisterDate() != null) {
                    Long houseTime = houseVO.getRegisterDate().getTime() / 1000;
                    if (houseTime > houseEndTime) {
                        attendFlag = false;
                    }
                }
                if (StringUtils.isNotBlank(houseVO.getAddressId())) {
                    List<SchoolDistrictVO> districtVOList = groupBy.get(houseVO.getAddressId());
                    if (!CollectionUtils.isEmpty(districtVOList)) {
                        for (SchoolDistrictVO schoolDistrictVO : districtVOList) {
                            if (xdList.contains(schoolDistrictVO.getSchoolCategory())) {
                                schoolDistrictVO.setAgeFlag(true);
                            } else {
                                schoolDistrictVO.setAgeFlag(false);
                            }
                            // 判断是否可就读
                            if (BoolEnum.TRUE
                                    .getType()
                                    .equals(schoolDistrictVO.getHouseEndTimeNo())) {
                                schoolDistrictVO.setAttendFlag(true);
                            } else {
                                schoolDistrictVO.setAttendFlag(attendFlag);
                            }
                        }
                    }
                    houseVO.setSchoolDistrictVOList(districtVOList);
                }
            }

        }

        dictHelper.valueToName(houseVOList, Arrays.asList(MyHouseEnum.values()));
        cache.put(key,houseVOList);
        return houseVOList;
    }

    @Override
    @OpApi(funcCode = "eduHouseJh0012", title = "金华当年适龄子女我的房产", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE,savelog = false)
    public List<EduHouseVO> getMyHouseInfoJh(AreaControlVO baseVO) {
        String idcard = SessionUtil.getSessionInfo().getIdcard();
        if(StringUtils.isBlank(idcard)){
            throw new AppException("用户的证件号码不能为空");
        }
        String key=idcard;
        Cache<String, List<EduHouseVO>> cache = JetCacheUtils.create(EduCache.EDU_MY_ENROLL_PRE_HOUSE, CacheType.BOTH, Duration.ofHours(6), Duration.ofSeconds(20));
        List<EduHouseVO> value=  cache.get(key);
        if(value!=null){
            return value;
        }
        if(StringUtils.isBlank(baseVO.getAreaCode())){
            //获取当前部署行政区划
            baseVO.setAreaCode(eduHelper.thisAreaCode());
        }
        EduOperationCacheQueryVO queryOpVO=new EduOperationCacheQueryVO();
        queryOpVO.setOperating("YW024");
        queryOpVO.setAreaCode(baseVO.getAreaCode());
        queryOpVO.setClassify("2");
        EduOperationCacheDetailVO fcOption=eduSystemConfigIntegration.getEduOperationOne(queryOpVO);
        int year=fcOption.getYear();
        QueryWrapper<EduStudentEnrollPre> studentEnrollPreQueryWrapper = new QueryWrapper<>();
        studentEnrollPreQueryWrapper
                .lambda()
                .eq(EduStudentEnrollPre::getYear, year)
                .and(
                        wrapper -> {
                            wrapper.eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                        });
        List<EduStudentEnrollPre> queryList =
                eduStudentEnrollPreService.list(studentEnrollPreQueryWrapper);

        if (CollectionUtils.isEmpty(queryList)) {
            cache.put(key,new ArrayList<>());
            return new ArrayList<>();
        }
        List<String> idcardList = new ArrayList<>();
        List<String> fmList = new ArrayList<>();
        List<String> xdList = new ArrayList<>();
        List<String> childList=new ArrayList<>();
        for (EduStudentEnrollPre pre : queryList) {
            idcardList.add(pre.getIdcard());
            childList.add(pre.getIdcard());
            if (StringUtils.isNotBlank(pre.getFatherIdcard())) {
                if (!fmList.contains(pre.getFatherIdcard())) {
                    fmList.add(pre.getFatherIdcard());
                }
            }
            if (StringUtils.isNotBlank(pre.getMotherIdcard())) {
                if (!fmList.contains(pre.getMotherIdcard())) {
                    fmList.add(pre.getMotherIdcard());
                }
            }
            if (!xdList.contains(pre.getSchoolCategory())) {
                xdList.add(pre.getSchoolCategory());
            }
        }
        idcardList.addAll(fmList);
        //去系统参数判断是否只能查询自己的房产
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("only_my_house_enroll");
        String onlyflag = commonIntegration.getValueByKey(commonVO);
        QueryWrapper<EduHouseDetail> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper
                .lambda()
                .eq(EduHouseDetail::getYear, year)
                .eq(EduHouseDetail::getStatus, BoolEnum.TRUE.getType());
        if("0".equalsIgnoreCase(onlyflag)||"false".equalsIgnoreCase(onlyflag)){
            detailQueryWrapper
                    .lambda()
                    .in(EduHouseDetail::getIdcard, idcardList);
        }else{
            List<String> cList=new ArrayList<>();
            cList.add(idcard);
            cList.addAll(childList);
            detailQueryWrapper
                    .lambda()
                    .in(EduHouseDetail::getIdcard, cList);
        }
        List<EduHouseDetail> detailList = eduHouseDetailService.list(detailQueryWrapper);
        if (CollectionUtils.isEmpty(detailList)) {
            return new ArrayList<>();
        }
        QueryWrapper<EduHouse> houseQueryWrapper=new QueryWrapper<>();
        houseQueryWrapper.lambda().in(EduHouse::getHouseId,detailList.stream().map(EduHouseDetail::getHouseId).distinct().collect(Collectors.toList()))
                .eq(EduHouse::getStatus,BoolEnum.TRUE.getType())
                .eq(EduHouse::getYear,year);
        List<EduHouse> houseList = eduHouseService.list(houseQueryWrapper);
        if(CollectionUtils.isEmpty(houseList)){
            cache.put(key,new ArrayList<>());
            return new ArrayList<>();
        }
        List<EduHouseVO> houseVOList =
                Convert.toList(
                        EduHouseVO.class,
                        houseList);
        Map<String, List<EduHouseVO>> realgroupBy = houseVOList.stream().collect(Collectors.groupingBy(EduHouseVO::getRealProperty));
        // 获取学区信息
        Map<String, List<SchoolDistrictVO>> groupBy = new HashMap<>();
        if (!CollectionUtils.isEmpty(houseVOList)) {

            // 没有年度参数则不获取房产学区
            Long houseEndTime =null;
            if(fcOption!=null&&fcOption.getEndTime()!=null){
                houseEndTime=fcOption.getEndTime().getTime()/1000;
            }
            if (houseEndTime != null) {
                List<String> addressIdList =
                        houseVOList.stream()
                                .map(EduHouseVO::getAddressId)
                                .distinct()
                                .collect(Collectors.toList());
                SchoolDistrictQueryVO queryVO = new SchoolDistrictQueryVO();
                queryVO.setAddressIdList(addressIdList);
                queryVO.setSchoolCategoryList(xdList);
                List<SchoolDistrictVO> schoolDistrictVOList =
                        eduAddressSchoolService.getSchoolInfo(queryVO);
                if (!CollectionUtils.isEmpty(schoolDistrictVOList)) {
                    dictHelper.valueToName(
                            schoolDistrictVOList, Arrays.asList(SchoolDictEnum.values()));
                    groupBy =
                            schoolDistrictVOList.stream()
                                    .collect(Collectors.groupingBy(SchoolDistrictVO::getAddressId));
                }
            }
            List<String> houseIdList =
                    houseVOList.stream().map(EduHouseVO::getHouseId).collect(Collectors.toList());
            QueryWrapper<EduComplaint> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .lambda().select(EduComplaint::getHandleStatus,EduComplaint::getOtherId)
                    .eq(EduComplaint::getType, '3')
                    .eq(EduComplaint::getHandleStatus, BoolEnum.FALSE.getType())
                    .in(EduComplaint::getOtherId, houseIdList);
            List<EduComplaint> complaints = eduComplaintService.list(queryWrapper);
            Map<String, String> complainMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(complaints)) {
                complainMap =
                        complaints.stream()
                                .collect(
                                        Collectors.toMap(
                                                EduComplaint::getOtherId,
                                                EduComplaint::getHandleStatus,
                                                (k1, k2) -> k1));
            }
            QueryWrapper<EduComplaint> queryInfoWrapper = new QueryWrapper<>();
            queryInfoWrapper
                    .lambda().select(EduComplaint::getHandleStatus,EduComplaint::getOtherId)
                    .eq(EduComplaint::getType, '2')
                    .eq(EduComplaint::getHandleStatus, BoolEnum.FALSE.getType())
                    .in(EduComplaint::getOtherId, houseIdList);
            List<EduComplaint> complaintsInfo = eduComplaintService.list(queryInfoWrapper);
            Map<String, String> complainInfoMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(complaintsInfo)) {
                complainInfoMap =
                        complaintsInfo.stream()
                                .collect(
                                        Collectors.toMap(
                                                EduComplaint::getOtherId,
                                                EduComplaint::getHandleStatus,
                                                (k1, k2) -> k1));
            }
            //获取报名情况
            QueryWrapper<EduStudentEnroll> enrollQueryWrapper=new QueryWrapper<>();
            List<String> enrollStatusList=new ArrayList<>();
            enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
            enrollQueryWrapper.lambda().select(EduStudentEnroll::getHouseId)
                    .in(EduStudentEnroll::getIdcard,childList)
                    .in(EduStudentEnroll::getEnrollStatus,enrollStatusList)
                    .isNotNull(EduStudentEnroll::getHouseId)
                    .eq(EduStudentEnroll::getYear,year);
            List<EduStudentEnroll> eduStudentEnrollList= eduStudentEnrollService.list(enrollQueryWrapper);
            List<String> enrollHouseIds=new ArrayList<>();
            if(!CollectionUtils.isEmpty(eduStudentEnrollList)){
                enrollHouseIds=eduStudentEnrollList.stream().map(EduStudentEnroll::getHouseId).distinct().collect(Collectors.toList());
            }
            for (EduHouseVO houseVO : houseVOList) {
                if(enrollHouseIds.contains(houseVO.getHouseId())){
                    houseVO.setEnrollFlag(true);
                }else{
                    houseVO.setEnrollFlag(false);
                }
                houseVO.setHouseHandleStatus(complainMap.get(houseVO.getHouseId()));
                houseVO.setHouseInfoHandleStatus(complainInfoMap.get(houseVO.getHouseId()));
                Boolean attendFlag = true;
                if (houseEndTime != null && houseVO.getRegisterDate() != null) {
                    Long houseTime = houseVO.getRegisterDate().getTime() / 1000;
                    if (houseTime > houseEndTime) {
                        attendFlag = false;
                    }
                }
                if (StringUtils.isNotBlank(houseVO.getAddressId())) {
                    List<EduHouseVO> allList=realgroupBy.get(houseVO.getRealProperty());
                    //暂时不对同意房产证不通地址的学区进行处理
                    List<SchoolDistrictVO> districtVOList = groupBy.get(houseVO.getAddressId());
                    if (!CollectionUtils.isEmpty(districtVOList)) {
                        for (SchoolDistrictVO schoolDistrictVO : districtVOList) {
                            if (xdList.contains(schoolDistrictVO.getSchoolCategory())) {
                                schoolDistrictVO.setAgeFlag(true);
                            } else {
                                schoolDistrictVO.setAgeFlag(false);
                            }
                            // 判断是否可就读
                            if (BoolEnum.TRUE
                                    .getType()
                                    .equals(schoolDistrictVO.getHouseEndTimeNo())) {
                                schoolDistrictVO.setAttendFlag(true);
                            } else {
                                schoolDistrictVO.setAttendFlag(attendFlag);
                            }
                        }
                    }
                    houseVO.setSchoolDistrictVOList(districtVOList);
                }
            }

        }

        dictHelper.valueToName(houseVOList, Arrays.asList(MyHouseEnum.values()));
        cache.put(key,houseVOList);
        return houseVOList;
    }


    /**
     * 处理houseId不为空的数据
     * @param year
     */
    private void initUseHouse(Integer year){
        //500条的进行查询，然后批量添加
        PageInfo<EduStudentEnroll> pageInfo=eduStudentHouseService.queryInit(year);
        if(!CollectionUtils.isEmpty(pageInfo.getList())){
            List<EduStudentEnroll> studentEnrollList = pageInfo.getList();
            List<EduStudentHouse> houseList = studentEnrollList.stream()
                    .filter(item->{
                        if (!ObjectUtils.isEmpty(item.getHouseId())){
                            return true;
                        }else{
                            return false;
                        }
                    })
                    .map(enroll -> {
                EduStudentHouse eduStudentHouse = Convert.convert(EduStudentHouse.class, enroll);
                eduStudentHouse.setStudentHouseId(IdUtil.simpleUUID());
                eduStudentHouse.setFinalSchoolId(enroll.getSchoolId());
                if (StringUtils.isNotBlank(enroll.getSchoolCategory())) {
                    eduStudentHouse.setSchollType(Integer.parseInt(enroll.getSchoolCategory()));
                }
                EduHouse eduHouse = eduHouseService.getHouseById(enroll.getHouseId());
                BeanUtil.copyProperties(eduHouse, eduStudentHouse);
                eduStudentHouse.setYear(year);
                eduStudentHouse.setStatus(BoolEnum.TRUE.getType());
                eduStudentHouse.setPersonId(getPersonId(enroll.getIdcard(), enroll.getCardType()));
                eduStudentHouse.setFatherId(getPersonId(enroll.getFatherIdcard(), enroll.getFatherCardType()));
                eduStudentHouse.setMotherId(getPersonId(enroll.getMotherIdcard(), enroll.getMotherCardType()));
                return eduStudentHouse;
            }).collect(Collectors.toList());
            eduStudentHouseService.saveBatch(houseList);
        }
        if(pageInfo.isHasNextPage()){
            this.initUseHouse(year);
        }
    }

    /**
     * 处理houseId为空的数据
     * @param year
     */
    private void initNoUserIdUserHouse(int year) {
        //查询公办学生数据处理
        QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
        ArrayList<String> configNameList = new ArrayList<>();
        configNameList.add("A");
        configNameList.add("C");
        queryWrapper.lambda()
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.lq.getType())
                .eq(EduStudentEnroll::getSchoolNature, SchoolNatureEnum.gb.getType())
                .isNull(EduStudentEnroll::getHouseId)
                .in(EduStudentEnroll::getConfigName,configNameList);
        List<EduStudentEnroll> list = eduStudentEnrollService.list(queryWrapper);
        List<String> idcardList = list.stream().map(EduStudentEnroll::getIdcard).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(idcardList)){
            idcardList.add("0");
        }
        queryWrapper.clear();
        //根据身份证查询其他报名数据，筛选出含有houseId的
        queryWrapper.lambda()
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getSchoolNature, SchoolNatureEnum.gb.getType())
                .isNotNull(EduStudentEnroll::getHouseId)
                .in(EduStudentEnroll::getIdcard,idcardList);
        List<EduStudentEnroll> studentEnrollList = eduStudentEnrollService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(studentEnrollList)){
            List<EduStudentHouse> houseList = studentEnrollList.stream()
                    .filter(item->{
                        if (!ObjectUtils.isEmpty(item.getHouseId())){
                            return true;
                        }else{
                            return false;
                        }
                    })
                    .filter(item ->{
                        QueryWrapper<EduStudentHouse> houseQueryWrapper = new QueryWrapper<>();
                        houseQueryWrapper.lambda().eq(EduStudentHouse::getHouseId,item.getHouseId());
                        if (eduStudentHouseService.count(houseQueryWrapper) > 0){
                            return false;
                        }else {
                            return true;
                        }
                    })
                    .map(enroll -> {
                EduStudentHouse eduStudentHouse = Convert.convert(EduStudentHouse.class, enroll);
                eduStudentHouse.setStudentHouseId(IdUtil.simpleUUID());
                eduStudentHouse.setFinalSchoolId(enroll.getSchoolId());
                if (StringUtils.isNotBlank(enroll.getSchoolCategory())) {
                    eduStudentHouse.setSchollType(Integer.parseInt(enroll.getSchoolCategory()));
                }
                EduHouse eduHouse = eduHouseService.getHouseById(enroll.getHouseId());
                BeanUtil.copyProperties(eduHouse, eduStudentHouse);
                eduStudentHouse.setYear(year);
                eduStudentHouse.setStatus(BoolEnum.TRUE.getType());
                eduStudentHouse.setPersonId(getPersonId(enroll.getIdcard(), enroll.getCardType()));
                eduStudentHouse.setFatherId(getPersonId(enroll.getFatherIdcard(), enroll.getFatherCardType()));
                eduStudentHouse.setMotherId(getPersonId(enroll.getMotherIdcard(), enroll.getMotherCardType()));
                return eduStudentHouse;
            }).collect(Collectors.toList());
            eduStudentHouseService.saveBatch(houseList);
        }
    }

    private Long getPersonId(String idcard,String cardType){
        if(StringUtils.isNotBlank(idcard)&&StringUtils.isNotBlank(cardType)){
            PersonInfo personInfo=personInfoService.selectByCardTypeAndIdcard(cardType,idcard);
            if(personInfo==null){
                return null;
            }
            return personInfo.getPersonId();
        }
        return null;
    }

    @Override
    @OpApi(funcCode = "eduHouse0013", title = "大数据房产信息表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduHouseVO> queryBigDataHouseInterface(HouseInterfaceSaveVO vo) {
        String idcard = vo.getIdcard();
        String areaCode = vo.getAreaCode();
        String name = vo.getName();
        if (StringUtils.isBlank(idcard)) {
            throw new AppException("请输入需要查询房产的身份证");
        }
        if (StringUtils.isBlank(name)) {
            throw new AppException("请输入需要查询房产的姓名");
        }
        if (!IdcardUtil.isValidCard(idcard)){
            throw new AppException("证件号码有误!");
        }
        //如果查询条件未选择统筹区，则将当前登陆用户的统筹区作为条件查询
        if (StringUtils.isBlank(areaCode)){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        ApiModel apiModel = eduHelper.getEduFunc("queryBigDataHouseInterface", vo.getAreaCode());
        try {
            Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
            if (null != bean) {
                List<EduHouseVO> list = (List<EduHouseVO>) apiModel.getMethod().invoke(bean, vo);
                if (CollectionUtils.isEmpty(list)) {
                    // 判断是否为空，为空则返回空参数
                    return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
                }
                // 不为空则获取分页结果
                PageInfo<EduHouseVO> pageInfo = new PageInfo<>(list);
                return pageInfo;
            } else {
                throw new AppException("未查询到方法");
            }
        }catch (AppException e ){
            throw e;
        }catch (InvocationTargetException e ){
            try{
                AppException exception= (AppException) e.getTargetException();
                throw new AppException(exception.getMsg(),e.getTargetException());
            }catch (Exception ex){
                throw new AppException(e.getCause().getMessage(),e.getTargetException());
            }

        }catch (Exception e ){
            throw new AppException( e.getMessage(),e);
        }
    }

    @Override
    @OpApi(funcCode = "eduHouse0014", title = "清除房产相关数据缓存", funcType = FuncTypeEnum.other)
    public void clearCache(EduHouseKeyVO vo) {
        this.clearCache(vo.getHouseId());
    }


    @Override
    @OpApi(funcCode = "eduHouse0015", title = "特殊通道人员维护房产大数据获取", funcType = FuncTypeEnum.query)
    public List<EduHouseVO> queryEnrollBeforeHouse(HouseInterfaceSaveVO vo) {
        String areaCode = vo.getAreaCode();
        if (StringUtils.isBlank(areaCode)) {
            areaCode = SessionUtil.getAreaCode();
        }
        if (StringUtils.isBlank(areaCode)) {
            areaCode = eduHelper.thisAreaCode();
        }
        if (StringUtils.isBlank(vo.getRealProperty())) {
            throw new AppException("请输入需要查询不动产权证号");
        }
        List<String> allIdcardList = new ArrayList<>();
        if (StringUtils.isNotBlank(vo.getIdcard())) {
            allIdcardList.add(vo.getIdcard());
        } else {
            if ("1".equals(vo.getHouseType())) {
                throw new AppException("请输入需要房产所属人身份证");
            } else {
                throw new AppException("请输入学生身份证");
            }
        }

        List<String> allNameList = new ArrayList<>();
        if (StringUtils.isNotBlank(vo.getName())) {
            allNameList.add(vo.getName());
        } else {
            if ("1".equals(vo.getHouseType())) {
                throw new AppException("请输入需要房产所属人姓名");
            } else {
                throw new AppException("请输入学生姓名");
            }
        }
        HouseInterfaceSaveVO saveVO = new HouseInterfaceSaveVO();
        saveVO.setIdcard(vo.getIdcard());
        saveVO.setName(vo.getName());
        saveVO.setAreaCode(areaCode);
        String studentEnrollPreId = vo.getStudentEnrollPreId();
        saveVO.setStudentEnrollPreId(studentEnrollPreId);
        if ("2".equals(vo.getHouseType())) {

            Boolean oneFlag = false;
            boolean flag = true;

            if (StringUtils.isBlank(vo.getFatherIdcard())) {
                oneFlag = true;
            } else {
                allIdcardList.add(vo.getFatherIdcard());
                allNameList.add(vo.getFatherName());
                flag = false;
            }
            if (StringUtils.isBlank(vo.getMotherIdcard())) {
                oneFlag = true;
            } else {
                allIdcardList.add(vo.getMotherIdcard());
                allNameList.add(vo.getMotherName());
                flag = false;
            }
            if (flag) {
                throw new AppException("请填写父母信息后查询");
            }

            saveVO.setFatherIdcard(vo.getFatherIdcard());
            saveVO.setFatherName(vo.getFatherName());
            saveVO.setMotherIdcard(vo.getMotherIdcard());
            saveVO.setMotherName(vo.getMotherName());
            saveVO.setOneFlag(oneFlag);
        }
        saveVO.setAllIdcardList(allIdcardList);
        saveVO.setAllNameList(allNameList);
        saveVO.setStudentEnrollPreId(vo.getStudentEnrollPreId());
        if (StringUtils.isBlank(vo.getSmallClassValue())) {
            throw new AppException("特殊通道类别不能为空");
        }
        List<String> glAddressList = new ArrayList<>();
        boolean syfc = false;
        if ("商业房产".equalsIgnoreCase(vo.getSmallClassValue())) {
            syfc = true;
            //获取商业房产关键字
            CommonVO commonVO = new CommonVO();
            commonVO.setAreaCode(areaCode);
            commonVO.setParamKey("edu_enroll_tstd_syfc");
            String glHouseAddress = commonIntegration.getValueByKeyAndArea(commonVO);
            glAddressList = StringUtils.isNotBlank(glHouseAddress) ? Arrays.stream(glHouseAddress.split(",")).map(s -> s).collect(Collectors.toList()) : new ArrayList<>();
        }
        List<EduHouseVO> retList = new ArrayList<>();
        QueryWrapper<EduHouseDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(EduHouseDetail::getHouseId).eq(EduHouseDetail::getRealProperty, Convert.toDBC(vo.getRealProperty()))
                .eq(EduHouseDetail::getYear, eduHelper.thisYear());
        List<EduHouseDetail> detailList = eduHouseDetailService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(detailList)) {
            QueryWrapper<EduHouse> houseQueryWrapper = new QueryWrapper<>();
            houseQueryWrapper.lambda().eq(EduHouse::getYear, eduHelper.thisYear())
                    .in(EduHouse::getHouseId, detailList.stream().map(EduHouseDetail::getHouseId).distinct().collect(Collectors.toList()));
            List<EduHouse> eduHouseList = eduHouseService.list(houseQueryWrapper);
            if (!CollectionUtils.isEmpty(eduHouseList)) {
                for (EduHouse eduHouse : eduHouseList) {
                    if (syfc) {
                        boolean conFlag = true;
                        //地址关键字过滤
                        if (!CollectionUtils.isEmpty(glAddressList)) {
                            for (String glStr : glAddressList) {
                                if (eduHouse.getAddress().contains(glStr)) {
                                    conFlag = false;
                                    break;
                                }
                            }
                        }
                        if (conFlag) {
                            continue;
                        }
                    }
                    retList.add(Convert.convert(EduHouseVO.class, eduHouse));
                }
                if (CollectionUtils.isEmpty(retList)) {
                    throw new AppException("该房产不能作为特殊通道（" + vo.getSmallClassValue() + "）使用,如有疑问，请联系基教科核实该房产是否可以使用");
                }
                return retList;
            }
        }

        ApiModel apiModel = eduHelper.getEduFunc("saveHouseInterfaceData", saveVO.getAreaCode());
        try {
            Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
            if (null != bean) {
                List<EduHouseVO> houseVOList = (List<EduHouseVO>) apiModel.getMethod().invoke(bean, saveVO);
                if (CollectionUtils.isEmpty(houseVOList)) {
                    throw new AppException("未查询到房产信息");
                }

                for (EduHouseVO eduHouseVO : houseVOList) {
                    if (!CollectionUtils.isEmpty(eduHouseVO.getDetailList())) {
                        boolean breakFlag = false;
                        for (EduHouseDetailVO eduHouseDetailVO : eduHouseVO.getDetailList()) {
                            if (eduHouseDetailVO.getRealProperty().equalsIgnoreCase(vo.getRealProperty())) {
                                breakFlag = true;
                                break;
                            }
                        }
                        if (breakFlag) {
                            if (syfc) {
                                boolean glFlag = false;
                                //地址关键字过滤
                                if (!CollectionUtils.isEmpty(glAddressList)) {
                                    for (String glStr : glAddressList) {
                                        if (eduHouseVO.getAddress().contains(glStr)) {
                                            glFlag = true;
                                            break;
                                        }
                                    }
                                }
                                if (!glFlag) {
                                    throw new AppException("该房产不能作为特殊通道（" + vo.getSmallClassValue() + "）使用,如有疑问，请联系基教科核实该房产是否可以使用");
                                }
                            }
                            retList.add(eduHouseVO);
                        }

                    }
                }
                if (StringUtils.isNotBlank(saveVO.getIdcard())) {
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(saveVO.getIdcard());

                }
                if (StringUtils.isNotBlank(saveVO.getFatherIdcard())) {
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(saveVO.getFatherIdcard());

                }
                if (StringUtils.isNotBlank(saveVO.getMotherIdcard())) {
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(saveVO.getMotherIdcard());
                }
                eduEnrollClearCacheHelper.clearCachePreBefore(vo.getStudentEnrollPreId());
                if (CollectionUtils.isEmpty(retList)) {
                    throw new AppException("未匹配到可使用的房产信息");
                }
                return retList;
            } else {
                throw new AppException("未查询到方法");
            }
        }catch (AppException e ){
            throw e;
        }catch (InvocationTargetException e ){
            try{
                AppException exception= (AppException) e.getTargetException();
                throw new AppException(exception.getMsg(),e.getTargetException());
            }catch (Exception ex){
                throw new AppException(e.getCause().getMessage(),e.getTargetException());
            }

        }catch (Exception e ){
            throw new AppException( e.getMessage(),e);
        }

    }

    @Override
    @OpApi(
            funcCode = "eduHouse0016",
            title = "幼儿园房产大数据接口信息获取",
            funcType = FuncTypeEnum.other)
    public void saveHouseNurseryInterfaceData(HouseInterfaceSaveVO vo) {
        String idcard=vo.getIdcard();
        if(StringUtils.isBlank(idcard)){
            throw new AppException("请传入需要同步房产的身份证信息");
        }
        String name=vo.getName();
        if(StringUtils.isBlank(name)){
            throw new AppException("请传入需要同步房产的姓名");
        }
        //判断当前年度是否已报名
        Boolean flag=this.checkEnroll(idcard,null);
        if(flag){
            throw new AppException("已报名，不能同步房产数据");
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        ApiModel apiModel=eduHelper.getEduFunc("saveHouseNurseryInterfaceData",vo.getAreaCode());
        try {
            Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
            if (null != bean) {
                List<EduHouseVO> list= (List<EduHouseVO>) apiModel.getMethod().invoke(bean, vo);
            }else {
                throw new AppException("未查询到方法");
            }
        }catch (AppException e ){
            throw e;
        }catch (InvocationTargetException e ){
            try{
                AppException exception= (AppException) e.getTargetException();
                throw new AppException(exception.getMsg(),e.getTargetException());
            }catch (Exception ex){
                throw new AppException(e.getCause().getMessage(),e.getTargetException());
            }

        }catch (Exception e ){
            throw new AppException( e.getMessage(),e);
        }
    }



    private Boolean checkEnroll(String idcard, Integer year) {
        if(year==null){
            year=eduHelper.thisYear();
        }
        List<String> enrollStatusList=new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        QueryWrapper<EduStudentEnroll> enrollQueryWrapper =new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnroll::getIdcard).eq(EduStudentEnroll::getIdcard,idcard)
                .eq(EduStudentEnroll::getYear,year)
                .in(EduStudentEnroll::getEnrollStatus,enrollStatusList);
        if(eduStudentEnrollService.count(enrollQueryWrapper)<=0){
            return false;
        }
        return true;
    }
}
